<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">

      <el-input v-model="listQuery.username" clearable class="filter-item" style="width: 200px;" placeholder="请输入名称"/>
      <el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 200px;" placeholder="请输入用户Id"/>
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入手机号"/>

      <el-select v-model="listQuery.virtualIs" clearable style="width: 200px" class="filter-item" placeholder="用户类型">
        <el-option v-for="(key, value) in userType" :key="key" :label="key" :value="value" />
      </el-select>

      <el-select v-model="listQuery.post" clearable style="width: 200px" class="filter-item" placeholder="用户等级">
        <el-option v-for="(key, value) in userLevel" :key="key" :label="key" :value="value +1" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="addmember">新增會員</el-button>
      <el-upload
            accept='.xls,.xlsx'
            ref="upload"
            :on-change="entry"
            :show-file-list='false'
            :auto-upload='false'
            action=""
            >
            <el-button type="primary" size="small" >導入</el-button>
        </el-upload>
        <!-- <el-button type="primary" size="small" @click="download">下载新增表格</el-button> -->
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" width="100px" label="用户ID" prop="id" sortable/>

      <el-table-column align="center" label="姓氏" prop="surname"/>

      <el-table-column align="center" label="名称" prop="username"/>

      <el-table-column align="center" label="手机号码" prop="mobile"/>

      <el-table-column align="center" label="性别" prop="gender">
        <template slot-scope="scope">
          <el-tag >{{ genderDic[scope.row.gender] }}</el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="生日" prop="birthday"/> -->

      <!-- <el-table-column align="center" label="用户等级" prop="userLevel">
        <template slot-scope="scope">
          <el-tag >{{ levelDic[scope.row.userLevel] }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="注册时间" prop="addTime" sortable/>

      <el-table-column align="center" label="注册时长/天" prop="registTime" sortable/>

      <el-table-column align="center" label="用户职级" prop="userLevel">
        <template slot-scope="scope">
          <el-tag >{{ userLevel[scope.row.post -1] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag>{{ statusDic[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="上月pv值" prop="lastPvValue" />

      <el-table-column align="center" label="操作" width="320" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="danger" size="mini" @click="disableds(scope.row)" v-if="scope.row.status!=1">冻结</el-button>
          <el-button type="warning"  size="mini" @click="userAddress(scope.row)">地址</el-button>
          <el-button type="success"  size="mini" @click="userCollection(scope.row)">收藏</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 用户地址 -->
    <el-dialog :visible.sync="userAddressVisible" title="用户地址">
      <el-table :data="addressList" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column align="center" label="收货人" prop="name" />
        <el-table-column align="center" label="省市" prop="province" />
        <el-table-column align="center" label="市" prop="city" />
        <el-table-column align="center" label="区" prop="county" />
        <el-table-column align="center" label="地址详情" prop="addressDetail" />
        <el-table-column align="center" label="手机号码" prop="tel" />
      </el-table>
    </el-dialog>

    <!-- 用户收藏 -->
    <el-dialog :visible.sync="userCollectionVisible" title="用户收藏">
      <el-table :data="collectionList" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column align="center" property="iconUrl" label="圖片">
          <template slot-scope="scope">
            <img :src="scope.row.imgUrl" width="40">
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格" prop="price" />
        <el-table-column align="center" label="库存" prop="num" />
        <el-table-column align="center" label="添加时间" prop="addTime" />
      </el-table>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 用户编辑对话框 -->
    <el-dialog :visible.sync="userDialogVisible" :title="isAdd==0?'用户编辑':'新增會員'">
      <el-form ref="userDetail" :rules="rules" :model="userDetail" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="姓氏" prop="surname">
          <el-input v-model="userDetail.surname"  />
        </el-form-item>
        <el-form-item  label="名称" prop="username">
          <el-input v-model="userDetail.username"  />
        </el-form-item>
  

        <!-- <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userDetail.nickname" />
        </el-form-item> -->
        <!--        <el-form-item label="用户密码" prop="mobile">-->
        <!--          <el-input v-model="userDetail.password" />-->
        <!--        </el-form-item>-->
        <!-- <el-form-item label="出生日期" prop="birthday">
          <el-input v-model="userDetail.birthday" />
        </el-form-item> -->
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="userDetail.birthday" type="datetime" placeholder="选择日期" format="MM-dd" value-format="yyyy-MM-dd" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="上级id" prop="parentId" v-show="false">
          <el-input v-model="userDetail.parentId" type="number" />
        </el-form-item>
        <el-form-item label="推荐人邀请码" prop="inviteCode2" >
          <el-input v-model="userDetail.inviteCode2" @change="getParentId" type="number" />
        </el-form-item>
        <el-form-item label="职位" prop="post">
          <!--          <el-input v-model="userDetail.post" />-->
          <el-select v-model="userDetail.post" @change="updataOprID" placeholder="请选择" ><el-option v-for="(item, index) in userLevel1" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item v-if="isAdd==0" label="个人/组织pv" prop="pvOne">
          <el-input v-model="userDetail.pvOne" />
        </el-form-item>
        <el-form-item label="是否接受推广信息" prop="acceptIs">
          <el-select @change="updataOprID" v-model="userDetail.acceptIs" placeholder="请选择"><el-option v-for="(item, index) in AcceptDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="userDetail.email" />
        </el-form-item>

        <el-form-item label="用户手机" prop="mobile">
          <el-input v-model="userDetail.mobile" @change="checktwe"/>
        </el-form-item>
        <el-form-item label="邀请码" prop="inviteCode">
          <el-input v-model="userDetail.inviteCode" />
        </el-form-item>
        <el-form-item label="用户性别" prop="gender">
          <el-select @change="updataOprID" v-model="userDetail.gender" placeholder="请选择"><el-option v-for="(item, index) in genderDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item label="用户等级" prop="userLevel">
          <el-select @change="updataOprID" v-model="userDetail.userLevel" placeholder="请选择"><el-option v-for="(item, index) in levelDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userDetail.status" placeholder="请选择"><el-option v-for="(item, index) in statusDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {findOrders} from '@/api/pv'
import XLSX from 'xlsx'
import { fetchList,fetchList2, userDetail, updateUser, addUser, userlistDao, getUserAddress,getAllTotal, getUserCollection,updateInviteCode,getAllLast } from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  name: 'User',
  components: { Pagination },
  data() {
    return {
      dictionary:{
          姓氏:'surname',
          名称: "username",
          出生日期:'birthday',
          上級ID:'parentId',
          邀請碼:'inviteCode',
          職位:'post',
          個人組織pv:'pvOne',
          是否接受推廣信息:'acceptIs',
          郵箱地址:"email",
          用戶手機號:'mobile',
          用戶性別:'gender',
          用戶等級:'userLevel',
          狀態:"status",
      },
      finalJson:null,
      rules: {
        surname:[{required: true, message: '請輸入姓', trigger: 'blur'}],
        username:[{required: true, message: '請輸入名称', trigger:'blur'},],
        // nickname:[{required:true,message:'請輸入用戶昵稱',trigger: 'blur'}],
        // birthday:[{required: true, message: '請輸入出生日期', trigger: 'blur'}],
        post:[{required: true, message: '請輸入職位', trigger: 'blur'}],
        acceptIs:[{required: true, message: '請輸入是否接受推廣信息', trigger: 'blur'}],
        mobile:[{required: true, message: '請輸入手機號', trigger: 'blur'}],
        userLevel:[{required: true, message: '請輸入用戶等級', trigger: 'blur'}],
        status:[{required: true, message: '請輸入狀態', trigger: 'blur'}],
        gender:[{required: true, message: '請輸入性别', trigger: 'blur'}],
      },
      list: null,
      addressList: null,
      collectionList: null,
      list1: null,
      total: 0,
      listLoading: true,
      listQuery2:{},
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        mobile: undefined,
        userId: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      downloadLoading: false,
      genderDic: ['未知', '男', '女'],
      levelDic: ['普通用户', 'VIP用户', '高级VIP用户'],
      userLevel: ['普通會員', '经销商', '副总监', '总监', '区域总监','高级区域总监', '亚洲总监', '亚太区总监', '环球总监'],
      userType: ['注册会员', '游客'],
      statusDic: ['可用', '禁用', '注销'],
      AcceptDic: ['不接受', '接受'],
      userLevel1: ['请选择', '普通會員', '经销商', '副总监', '总监', '区域总监','高级区域总监', '亚洲总监', '亚太区总监', '环球总监'],
      userDialogVisible: false,
      userAddressVisible: false,
      userCollectionVisible: false,
      userDetail: {
        post:0,
        acceptIs:0,
        inviteCode2:'',
      },
      isAdd: 1
    }
  },
  created() {
    this.getList()
  },
  methods: {
    updataOprID(){
      this.$forceUpdate()
    },
    download(){
        window.open('/duser.xlsx')
    },
    getParentId(){
      
    },
    getDate(val){
       let dateArr=val.split('/')
       if(dateArr[1].length==1){
         dateArr[1]='0'+dateArr[1]
       }
       if(dateArr[2].length==1){
         dateArr[2]='0'+dateArr[2]
       }
       return dateArr[0]+'-'+dateArr[1]+'-'+dateArr[2]
    },
    entry(file,fileList){
      let files = {0:file.raw}
      this.readExcel1(files);
    },
    readExcel1(files) {//表格导入
        var that = this;

        if(files.length<=0){//如果没有文件名
            return false;
        }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
            this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
            return false;
        }
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
            try {
                const data = ev.target.result;
                const workbook = XLSX.read(data, {
                    type: 'binary'
                });
                const wsname = workbook.SheetNames[0];//取第一张表
                const ws = XLSX.utils.sheet_to_csv(workbook.Sheets[wsname]);//生成json表格内容
                // let temp1=ws.substr(ws.indexOf("序号"), ws.length-1)
                // let temp2=temp1.replace('平段电量,,,高峰,,,低估,,,变压器基本电费,,最大需量基本电费,,力率调整电费,,合计,,,','平段电量,平段电价,平段电费,高峰电量,高峰电价,高峰电费,低估电量,低估电价,低估电费,变压器基本电费容量,变压器基本电费金额,最大需量基本电费容量,最大需量基本电费金额,力率调整电费增收,力率调整电费减收,合计电量,合计平均电价,合计电费,')
                // let temp3=temp2.replace(',,,,,,,,,,,,电量,单价,电费,电量,电价,电费,电量,电价,电费,容量,金额,容量,金额,增收,减收,电量,平均电价,电费,,,,,,,,,,,','')
                // let temp4=temp3.substr(0, temp3.indexOf(",,,,,,"))
                this.replaceLoop(ws)
                 this.uploadData(this.csvJSON(this.finalJson))
            } catch (e) {
                return false;
            }
        };
        fileReader.readAsBinaryString(files[0]);
    },
    uploadData(data){
      for (let index = 0; index < data.length; index++) {
        
          let dataObj={
            ...data[index],
            acceptIs:Number(data[index].acceptIs),
            gender:Number(data[index].gender),
            parentId:Number(data[index].parentId),
            post:Number(data[index].post),
            status:Number(data[index].status),
            userLevel:Number(data[index].userLevel),
            birthday:this.getDate(data[index].birthday),
   
          }
         
          if(data[index].mobile==''){
            return true
          }
          addUser(dataObj)
            .then((response) => {
              if (response.data.errno == 0) {
                this.userDialogVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新用户成功'
                })
              } else {
                this.$notify.error({
                  title: '添加失敗，可能是名称重複',
                  message: response.data.errmsg
                })
              }
            })
      }
      
    },
    csvJSON(csv){
            var lines=csv.split("\n");
            var result = [];
            var headers=lines[0].split(",");

            for(var i=1;i<lines.length;i++){
                var obj = {};
  
                var currentline=lines[i].trim().split(",");
                if(lines[i]!=''){
                    for(var j=0;j<headers.length;j++){
                        obj[headers[j].trim()] = currentline[j];
                    }
                    result.push(obj);
                }
            }
            return result; //JSON
        },
    replaceLoop(obj) {
        for (const key in this.dictionary) {
            if (this.dictionary.hasOwnProperty(key)) {
                if(obj.indexOf(key)>-1){
                    this.finalJson=obj.replace(key,this.dictionary[key])
                    this.replaceLoop(this.finalJson)
                    break
                }
            }
        }
    },
    checktwe(e){

      let lackLength=0
      if(e.length<12){
        lackLength=12-e.length
      }
      let get0=''
      for (let index = 0; index < lackLength; index++) {
        get0+='0'
        
      }
      this.$set(this.userDetail,'inviteCode',get0+e)
    },
    addmember() {
      this.isAdd = 1
      this.userDetail = {}
      this.userDetail.post=1
      this.userDetail.acceptIs=0
      this.userDetail.gender=0
      this.userDetail.status=0
      this.userDetail.userLevel=0
      this.userDialogVisible = true
    },
    groupOrg(row) {
      const routerData = this.$router.resolve({
        path: '/tree',
        query: {
          userId: row.id
        }
      })
      window.open(routerData.href, '_blank')
    },
    async getList() {
      this.listLoading = true
        let response5=await getAllLast({})
      if (this.listQuery.userId) {
        userDetail(this.listQuery.userId).then(response => {
          this.list = []
          if (response.data.data) {
            this.list.push(response.data.data)
            for (let index = 0; index < this.list.length; index++) {
                const element = this.list[index];
                element['lastPvValue']=0
                for (let i = 0; i < response5.data.length; i++) {
                    const element4 = response5.data[i];
                    if(element.id == element4.user_id){
                        element['lastPvValue']+=Number(element4.integral_price)
                    }
                }
            }
            this.total = 1
            this.listLoading = false
          } else {
            this.list = []
            this.total = 0
            this.listLoading = false
          }
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      } else {
        fetchList(this.listQuery).then(response => {
          this.list = response.data.data.list

           for (let index = 0; index < this.list.length; index++) {
                const element = this.list[index];
                element['lastPvValue']=0
                for (let i = 0; i < response5.data.length; i++) {
                    const element4 = response5.data[i];
                    if(element.id == element4.user_id){
                        element['lastPvValue']+=Number(element4.integral_price)
                    }
                }
            }
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDownload() {
        this.downloadLoading =true
        this.listQuery2=Object.assign({},this.listQuery)
        this.listQuery2.page=1
        this.listQuery2.limit=10000
        
        if (this.listQuery2.userId) {
            let list2=[]
            userDetail(this.listQuery2.userId).then(response => {
                this.list1 = []
                if (response.data.data) {
                    this.list1.push(response.data.data)
                }
                userlistDao(this.listQuery2).then(response2 => {
                    let list = response2.data.data.list;
                     for (let i = 0; i < this.list1.length; i++) {
                        for (let j = 0; j < list.length; j++) {
                            if(this.list1[i].id==list[j].id){
                                list2[0]=Object.assign(this.list1[i],list[j])
                            }
                        }
                    }
                    userDetail(list2[0].parentId).then(response3 => {
                        list2[0].parentName=response3.data.data.surname+response3.data.data.username
                        for (let index = 0; index < list2.length; index++) {
                            const element = list2[index];
                            element.birthday && (element.birthday=element.birthday.replace("00:00:00",'').substring(5))
                            element.postName=this.userLevel[element.post-1] 
                        }
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = ['会员编号', '姓氏','名称', '手机号码', '电子邮箱', '性别', '推荐人', '会员等级', '生日', '消费总金额', '消费次数', '注册日期', '最后消费日期']
                            const filterVal = ['id', 'surName','userName', 'mobile', 'email', 'sex', 'parentName', 'postName', 'birthday', 'actualPrice', 'actualCount', 'addTime', 'actualTime']
                            excel.export_json_to_excel2(tHeader, list2, filterVal, '用户信息')
                            this.downloadLoading = false
                        })
                    })
                })
            })
        }else{
            userlistDao(this.listQuery2).then(response => {
                this.list1 = response.data.data.list
                fetchList(this.listQuery2).then(response2 => {
                    let list = response2.data.data.list
                    for (let j = 0; j < this.list1.length; j++) {
                        for (let i = 0; i < list.length; i++) {
                            if(this.list1[j].id==list[i].id){
                                this.list1[j]['parentId']=list[i].parentId
                            }
                        }
                    }
                    for (let i = 0; i < this.list1.length; i++) {
                        for (let j = 0; j < this.list1.length; j++) {
                            if(this.list1[i].parentId==this.list1[j].id){
                                this.list1[i].parentName=this.list1[j].surName+this.list1[j].userName
                            }
                        }
                    }
                    for (let index = 0; index < this.list1.length; index++) {
                        const element = this.list1[index];
                        element.birthday && (element.birthday=element.birthday.replace("00:00:00",'').substring(5))
                        element.postName=this.userLevel[element.post-1] 
                    }
                    import('@/vendor/Export2Excel').then(excel => {
                        const tHeader = ['会员编号', '姓氏','名称', '手机号码', '电子邮箱', '性别', '推荐人', '会员等级', '生日', '消费总金额', '消费次数', '注册日期', '最后消费日期']
                        const filterVal = ['id', 'surName','userName', 'mobile', 'email', 'sex', 'parentName', 'postName', 'birthday', 'actualPrice', 'actualCount', 'addTime', 'actualTime']
                        excel.export_json_to_excel2(tHeader, this.list1, filterVal, '用户信息')
                        this.downloadLoading = false
                    })
                })
            }).catch(() => {
                this.list1 = []
                this.downloadLoading = false
            })
        }

      
        
    },
    randomn(n) {
      if (n > 21) return null
      return parseInt((Math.random() + 1) * Math.pow(10,n-1))
    },
    disableds(row){
        this.$confirm('此操作将冻结该用户, 是否继续?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            let userDetail = row
            userDetail.mobile=this.getNowFormatDate()+row.mobile
            userDetail.inviteCode=this.getNowFormatDate()+row.inviteCode
            userDetail.email=this.getNowFormatDate()+row.email
            userDetail.status=1

      updateUser(userDetail)
            .then((response) => {
              this.userDialogVisible = false
              updateInviteCode({userid:this.userDetail.id,inviteCode:userDetail.inviteCode}).then((res)=>{})
              this.$notify.success({
                title: '成功',
                message: '更新用户成功'
              })
              fetchList(this.listQuery).then(response => {
                  this.list = response.data.data.list
                  this.total = response.data.data.total
                  this.listLoading = false
                }).catch(() => {
                  this.list = []
                  this.total = 0
                  this.listLoading = false
                })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }).catch(() => {
                    
        });

      
    },
    getNowFormatDate() {
      var date = new Date();
      var seperator1 = "";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    handleDetail(row) {
      this.isAdd = 0
      this.userDetail = row
      userDetail(row.id).then(async response => {
          if (response.data.data) {
            let pvTotal=0
            let response3=await getAllTotal({})
            for (let i = 0; i < response3.data.length; i++) {
                const element2 = response3.data[i];
                if(row.id == element2.user_id){
                    pvTotal+=Number(element2.integral_price)
                }
            }
            this.$set(this.userDetail,'pvOne',pvTotal)
            userDetail(row.parentId).then(response2 => {
                if (response2.data.data) {
                

                    this.$set(this.userDetail,'inviteCode2',response2.data.data.inviteCode)
                } 
            })
            this.userDialogVisible = true
                
           
            
          } 
        })
      
     
    },
    handleUserUpdate() {
      this.$refs['userDetail'].validate((valid) => {
        if (valid) {
            
            this.listQuery.inviteCode=this.userDetail.inviteCode2
            let listQuery=Object.assign({},this.listQuery)

            delete listQuery.mobile
            fetchList2(listQuery).then(response => {
                if (response.data.data) {
                    this.userDetail.parentId=response.data.data.list[0].id
                } 
                if(!this.userDetail.parentId && this.userDetail.inviteCode2 && this.userDetail.inviteCode2!=''){
                    this.$notify.error({
                        title: '温馨提示',
                        message: '不正确的推荐人邀请码'
                        })
                    return
                    }
                if(this.userDetail.parentId==this.userDetail.id && this.userDetail.id){
                    this.$notify.error({
                        title: '温馨提示',
                        message: '上级id不能为当前用户id'
                        })
                    return
                    }
                    if(this.userDetail.inviteCode==this.userDetail.inviteCode2){
                    this.$notify.error({
                        title: '温馨提示',
                        message: '邀请人推荐码和邀请码不能相等'
                        })
                    return
                    }
                if (this.isAdd == 0) {
                    updateUser(this.userDetail)
                    .then((response) => {
                    this.userDialogVisible = false

                    updateInviteCode({userid:this.userDetail.id,inviteCode:this.userDetail.inviteCode}).then((res)=>{})

                    this.$notify.success({
                        title: '成功',
                        message: '更新用户成功'
                    })
                    fetchList(listQuery).then(response => {
                        this.list = response.data.data.list
                        this.total = response.data.data.total
                        this.listLoading = false
                        }).catch(() => {
                        this.list = []
                        this.total = 0
                        this.listLoading = false
                        })
                    })
                    .catch(response => {
                        this.$notify.error({
                            title: '失败',
                            message: '修改失败'
                        })
                    })
                } else {
                    this.userDetail.parentId=Number(this.userDetail.parentId)
                    addUser(this.userDetail)
                    .then((response) => {
                        if (response.data.errno == 0) {
                            this.userDialogVisible = false
                            this.$notify.success({
                            title: '成功',
                            message: '更新用户成功'
                            })
                            fetchList(listQuery).then(response => {
                            this.list = response.data.data.list
                            this.total = response.data.data.total
                            this.listLoading = false
                            }).catch(() => {
                            this.list = []
                            this.total = 0
                            this.listLoading = false
                        })
                    } else {
                            this.$notify.error({
                                title: '添加失敗，可能是名称重複',
                                message: response.data.errmsg
                            })
                        }
                    })
                    .catch(response => {
                        this.$notify.error({
                            title: '失败',
                            message: response.data.errmsg
                        })
                    })
                }
            })
        }
      })
    },
    userAddress(row) {
      getUserAddress(row.id)
        .then((response) => {
          this.addressList = response.data.data
          this.userAddressVisible = true
        })
    },
    userCollection(row) {
      getUserCollection(row.id)
        .then((response) => {
          this.collectionList = response.data.data
          this.userCollectionVisible = true
        })
    }
  }
}
</script>
